package com.spbl.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.spbl.common.config.ErrorTypeEnum;
import com.spbl.common.exception.BusinessException;
import com.spbl.common.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Description(构造拦截器)
 * author: Gao xueyong
 * Create at: 2020/5/30 3:26 下午
 */
@Slf4j
@Component
public class VerfyInterceptor extends HandlerInterceptorAdapter {

    /**
     * 在业务处理器处理请求之前被调用。预处理，可以进行编码、安全控制、权限校验等处理
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        log.info("请求地址[{}], 请求参数[{}]", request.getRequestURI(), JSONObject.toJSON(request.getParameterMap()));
        //request.getHeader(String) 从请求头中获取数据
        //从请求头中获取用户token（登陆凭证根据业务而定）

        String token = request.getHeader("H-User-Token");
        if(StringUtils.isEmpty(token)){
            log.error("toekn校验失败！未获取到token");
            throw new BusinessException(ErrorTypeEnum.TOKEN_ERROR.getCode(),"token校验失败！未获取到token");
        }
        Boolean valid = JwtUtils.verifyRSA256Token(token);
        if(!valid){
            log.error("toekn校验失败！请检查");
            throw new BusinessException(ErrorTypeEnum.TOKEN_ERROR.getCode(),"token校验失败！请检查");
        }
        //这里的异常是我自定义的异常，系统抛出异常后框架捕获异常然后转为统一的格式返回给前端， 其实这里也可以返回false
//        throw new FastRuntimeException(20001,"No access");
        return true;
    }

    /**
     * 在业务处理器处理请求执行完成后，生成视图之前执行。后处理（调用了Service并返回ModelAndView，但未进行页面渲染），有机会修改ModelAndView
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    /**
     * 在DispatcherServlet完全处理完请求后被调用，可用于清理资源等。返回处理（已经渲染了页面）
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }


    /**
     * 校验用户访问权限
     *
     * @param userId
     * @param requestURI
     * @return
     */
    private boolean checkAuth(Long userId, String requestURI) {
        return true;
    }
}
